<?php
namespace doumiaoduo\telecaptcha;

use yii\validators\Validator;

trait TelecaptchaTrait{

    public $telecaptcha;

    public function init(){
        parent::init();
        $validators = $this->getValidators();
        /**$options = ['requiredValue'=>$this->getSmsCode(),'message'=>'手机验证码输入错误'];
        $validators->append(Validator::createValidator('required',$this,'telecaptcha',$options));*/
    }

    public function changeTelevalidateRule($rule, $options=[]){
        $validators = $this->getValidators();
        $validators->append(Validator::createValidator($rule,$this,'telecaptcha',$options));
    }

    //获取当前session中存放的sms_code
    public function getSmsCode($telephone = ''){
//        if(YII_ENV == 'dev'){
//            return '123456';//为测试用的，后期需删除
//        }

        $smstelephone_cache = \Yii::$app->cache->get('smscode_'.$telephone);//如果为空，说明该手机号没有点击获取验证码的操作
        if(empty($smstelephone_cache)){
            return 88888888;
        }

        //检查session是否打开
        if(!\Yii::$app->session->isActive){
            \Yii::$app->session->open();
        }
        $signup_sms_code = intval(\Yii::$app->session->get('login_sms_code'));
        $signup_sms_time = \Yii::$app->session->get('login_sms_time')?\Yii::$app->session->get('login_sms_time'):0;
        if(time()-$signup_sms_time<1800){
            //小于5分钟60s*50,改为小于半小时30*60s=1800s
            return $signup_sms_code;
        }else{
            return 88888888;//正确的验证码是6位的
        }
    }
}
?>